package com.example.beans;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.ObjectCodec;
import com.fasterxml.jackson.databind.*;
import org.springframework.boot.jackson.JsonComponent;
import org.springframework.boot.jackson.JsonObjectDeserializer;
import org.springframework.boot.jackson.JsonObjectSerializer;

import java.io.IOException;

/**
 * 对json返回的格式做一个序列化和反序列化操作
 */
@JsonComponent
public class UserCustomJSON {
    //    定义一个序列化类继承JsonSerializer
    public static class Serializer extends JsonObjectSerializer<User> {


        @Override
        protected void serializeObject(User user, JsonGenerator jgen, SerializerProvider provider) throws IOException {
            jgen.writeObjectField("id",user.getId());
            jgen.writeObjectField("username","testSerializer");
        }
    }

    //    定义一个反序列化类继承JsonDeserializer
    public static class DeSerializer extends JsonObjectDeserializer<User> {

        @Override
        protected User deserializeObject(JsonParser jsonParser, DeserializationContext context, ObjectCodec codec, JsonNode tree) throws IOException {
            User user = new User();
            user.setId(tree.findValue("id").asInt());

            return user;
        }
    }
}
